package com.lanxin.auth.interceptor;

import com.lanxin.enums.HttpStatusEnum;
import com.lanxin.handler.BaseException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @author cyh
 * @create 2025-09-29 10:56
 */
public class JwtHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes != null ? attributes.getRequest() : null;
        // 获取http请求中的jwt令牌
        if (request != null) {
            try {
                String authorizationHeader = request.getHeader("Authorization");
                String jwtSecret = "lanxin";
                // 检查Token是否存在
                if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
                    String jwtToken = authorizationHeader.replace("Bearer ", "");
                    // 解析和验证JWT
                    Claims claims = Jwts.parser()
                            .setSigningKey(jwtSecret)
                            .parseClaimsJws(jwtToken)
                            .getBody();
                    // 从 JWT 中获取数据
                    Date expirationTime = claims.getExpiration();  //获取加密中的过期时间
                    // 判断过期时间是否大于当前时间
                    if (expirationTime.before(new Date())) {
                        throw new BaseException(HttpStatusEnum.FORBIDDEN.getCode(),"JWT 令牌已过期！");
                    }
                    return true;
                }
            } catch (JwtException e) {
                // 处理JWT解析异常
                throw new BaseException(HttpStatusEnum.FORBIDDEN.getCode(),"无效的JWT令牌！"+e.getMessage());
            } catch (Exception e) {
                // 处理其他可能的异常情况
                throw new BaseException(HttpStatusEnum.FORBIDDEN.getCode(),"发生异常：" + e.getMessage());
            }
        }
        throw new BaseException(HttpStatusEnum.FORBIDDEN.getCode(),"暂无权限");
    }

}
